// popup.js - Popup UI logic and interactions
class PopupManager {
  constructor() {
    this.rules = new Map();
    this.currentEditingRule = null;
    this.logs = [];
    this.pageRequests = new Map(); // 存储页面请求记录
    this.init();
  }

  async init() {
    await this.loadRules();
    this.setupEventListeners();
    this.renderRules();
    this.renderLogs();
    // 初始化时加载页面请求并填充选择器
    await this.loadPageRequests();
    this.populateApiSelector();
    
    // 移除自动刷新机制，改为只有手动刷新
  }

  async loadRules() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'GET_RULES' });
      if (response && response.success) {
        this.rules = new Map(Object.entries(response.data));
      }
    } catch (error) {
      // 静默处理Service Worker未就绪的情况
      this.rules = new Map();
    }
  }

  setupEventListeners() {
    // 标签页切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.addEventListener('click', () => this.switchTab(btn.dataset.tab));
    });

    // 添加规则按钮
    document.getElementById('addRuleBtn').addEventListener('click', () => {
      this.openRuleModal();
    });

    // 搜索功能
    document.getElementById('searchInput').addEventListener('input', (e) => {
      this.filterRules(e.target.value);
    });

    // 模态框相关
    document.getElementById('closeModalBtn').addEventListener('click', () => {
      this.closeRuleModal();
    });

    document.getElementById('cancelBtn').addEventListener('click', () => {
      this.closeRuleModal();
    });

    // 模态框外点击关闭
    document.getElementById('ruleModal').addEventListener('click', (e) => {
      if (e.target.id === 'ruleModal') {
        this.closeRuleModal();
      }
    });

    // 表单提交
    document.getElementById('ruleForm').addEventListener('submit', (e) => {
      e.preventDefault();
      this.saveRule();
    });

    // 请求/响应修改复选框
    document.getElementById('enableRequestMod').addEventListener('change', (e) => {
      this.toggleModificationSection('requestModSection', e.target.checked);
    });

    document.getElementById('enableResponseMod').addEventListener('change', (e) => {
      this.toggleModificationSection('responseModSection', e.target.checked);
    });

    // 清除日志
    document.getElementById('clearLogsBtn').addEventListener('click', () => {
      this.clearLogs();
    });

    // 接口选择器事件
    document.getElementById('apiSelector').addEventListener('change', (e) => {
      this.handleApiSelection(e.target.value);
    });

    // 刷新接口按钮
    document.getElementById('refreshApisBtn').addEventListener('click', () => {
      this.refreshApiList();
    });

    // 快捷键
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        this.closeRuleModal();
      }
    });
  }

  switchTab(tabName) {
    // 更新标签按钮状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.classList.toggle('active', btn.dataset.tab === tabName);
    });

    // 显示对应内容
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.toggle('active', content.id === tabName + 'Tab');
    });

    // 如果切换到日志标签，刷新日志
    if (tabName === 'logs') {
      this.renderLogs();
    }
  }

  openRuleModal(rule = null) {
    this.currentEditingRule = rule;
    const modal = document.getElementById('ruleModal');
    const form = document.getElementById('ruleForm');
    const title = document.getElementById('modalTitle');

    if (rule) {
      title.textContent = '编辑拦截规则';
      this.populateForm(rule);
    } else {
      title.textContent = '添加拦截规则';
      form.reset();
      this.resetModificationSections();
      // 清空接口选择器和信息区域
      this.resetApiSelection();
    }

    // 打开模态框时填充API选择器（使用当前已加载的数据）
    this.populateApiSelector();

    modal.style.display = 'block';
    // 不再需要焦点到规则名称字段
  }

  async refreshApiList() {
    // 保存当前选中的接口ID
    const currentSelection = document.getElementById('apiSelector').value;
    
    // 重新加载页面请求
    await this.loadPageRequests();
    
    // 重新填充下拉框
    this.populateApiSelector();
    
    // 恢复之前的选择（如果该接口仍然存在）
    if (currentSelection && this.pageRequests.has(currentSelection)) {
      document.getElementById('apiSelector').value = currentSelection;
      // 重新显示接口信息
      this.handleApiSelection(currentSelection);
    }
  }

  async loadPageRequests() {
    try {
      // 在DevTools Panel中，需要使用不同的方式获取标签页ID
      let tabId = null;
      
      // 尝试从chrome.devtools获取inspected窗口的标签页ID
      if (typeof chrome !== 'undefined' && chrome.devtools && chrome.devtools.inspectedWindow) {
        tabId = chrome.devtools.inspectedWindow.tabId;
      } else {
        // 如果不在DevTools环境中，获取当前活动标签页
        try {
          const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
          if (tab) {
            tabId = tab.id;
          }
        } catch (error) {
          console.warn('无法获取当前标签页ID:', error);
        }
      }

      if (!tabId) {
        console.warn('无法获取标签页ID');
        this.pageRequests = new Map();
        return;
      }

      // 向background script请求页面请求记录
      const response = await chrome.runtime.sendMessage({ 
        type: 'GET_PAGE_REQUESTS',
        tabId: tabId 
      });

      if (response.success) {
        this.pageRequests = new Map(Object.entries(response.data || {}));
        // 移除自动调用populateApiSelector，避免清空用户选择
      }
    } catch (error) {
      console.error('加载页面请求失败:', error);
      this.pageRequests = new Map();
    }
  }

  populateApiSelector() {
    const selector = document.getElementById('apiSelector');
    selector.innerHTML = '<option value="">请选择一个接口...</option>';

    if (this.pageRequests.size === 0) {
      const option = document.createElement('option');
      option.value = '';
      option.textContent = '暂无请求记录，请在页面中发起一些API请求';
      option.disabled = true;
      selector.appendChild(option);
      return;
    }

    // 按时间戳倒序排列（最新的在前面）
    const sortedRequests = Array.from(this.pageRequests.entries())
      .sort((a, b) => b[1].timestamp - a[1].timestamp);

    sortedRequests.forEach(([requestId, request]) => {
      const option = document.createElement('option');
      option.value = requestId;
      
      // 显示更详细的信息：方法 + URL路径 + 状态码
      try {
        const url = new URL(request.url);
        const path = url.pathname + url.search;
        const status = request.status ? ` [${request.status}]` : '';
        option.textContent = `${request.method} ${this.truncateUrl(path, 40)}${status}`;
      } catch (error) {
        // 如果URL解析失败，直接显示原始URL
        const status = request.status ? ` [${request.status}]` : '';
        option.textContent = `${request.method} ${this.truncateUrl(request.url, 40)}${status}`;
      }
      
      selector.appendChild(option);
    });
  }

  handleApiSelection(requestId) {
    const apiInfoSection = document.getElementById('apiInfoSection');
    
    if (!requestId) {
      apiInfoSection.style.display = 'none';
      return;
    }

    const request = this.pageRequests.get(requestId);
    if (!request) {
      apiInfoSection.style.display = 'none';
      return;
    }

    // 显示接口信息
    this.displayApiInfo(request);
    
    // 自动填充表单
    this.autoFillFormFromRequest(request);
    
    apiInfoSection.style.display = 'block';
  }

  displayApiInfo(request) {
    const methodElement = document.getElementById('selectedApiMethod');
    const urlElement = document.getElementById('selectedApiUrl');
    
    methodElement.textContent = request.method;
    methodElement.className = `api-method ${request.method}`;
    urlElement.textContent = request.url;
  }

  autoFillFormFromRequest(request) {
    // 如果有请求数据，自动启用并填充请求修改
    if (request.requestHeaders || request.requestBody) {
      document.getElementById('enableRequestMod').checked = true;
      this.toggleModificationSection('requestModSection', true);
      
      if (request.requestHeaders) {
        document.getElementById('requestHeaders').value = 
          JSON.stringify(request.requestHeaders, null, 2);
      }
      
      if (request.requestBody) {
        document.getElementById('requestBody').value = 
          JSON.stringify(request.requestBody, null, 2);
      }
    }

    // 如果有响应数据，自动启用并填充响应修改
    if (request.responseHeaders || request.responseBody) {
      document.getElementById('enableResponseMod').checked = true;
      this.toggleModificationSection('responseModSection', true);
      
      document.getElementById('responseStatus').value = request.status || 200;
      
      if (request.responseHeaders) {
        document.getElementById('responseHeaders').value = 
          JSON.stringify(request.responseHeaders, null, 2);
      }
      
      if (request.responseBody) {
        document.getElementById('responseBody').value = 
          JSON.stringify(request.responseBody, null, 2);
      }
    }
  }

  resetApiSelection() {
    document.getElementById('apiSelector').value = '';
    document.getElementById('apiInfoSection').style.display = 'none';
  }

  truncateUrl(url, maxLength = 50) {
    if (url.length <= maxLength) return url;
    return url.substring(0, maxLength) + '...';
  }

  closeRuleModal() {
    document.getElementById('ruleModal').style.display = 'none';
    this.currentEditingRule = null;
  }

  populateForm(rule) {
    // 请求修改
    const hasRequestMod = rule.requestModification;
    document.getElementById('enableRequestMod').checked = hasRequestMod;
    this.toggleModificationSection('requestModSection', hasRequestMod);

    if (hasRequestMod) {
      document.getElementById('requestHeaders').value = 
        rule.requestModification.headers ? JSON.stringify(rule.requestModification.headers, null, 2) : '';
      document.getElementById('requestBody').value = 
        rule.requestModification.body ? JSON.stringify(rule.requestModification.body, null, 2) : '';
    }

    // 响应修改
    const hasResponseMod = rule.responseModification;
    document.getElementById('enableResponseMod').checked = hasResponseMod;
    this.toggleModificationSection('responseModSection', hasResponseMod);

    if (hasResponseMod) {
      document.getElementById('responseStatus').value = rule.responseModification.status || 200;
      document.getElementById('responseDelay').value = rule.responseModification.delay || 0;
      document.getElementById('responseHeaders').value = 
        rule.responseModification.headers ? JSON.stringify(rule.responseModification.headers, null, 2) : '';
      document.getElementById('responseBody').value = 
        rule.responseModification.body ? JSON.stringify(rule.responseModification.body, null, 2) : '';
    }
  }

  resetModificationSections() {
    document.getElementById('enableRequestMod').checked = false;
    document.getElementById('enableResponseMod').checked = false;
    this.toggleModificationSection('requestModSection', false);
    this.toggleModificationSection('responseModSection', false);
  }

  toggleModificationSection(sectionId, show) {
    const section = document.getElementById(sectionId);
    section.classList.toggle('active', show);
  }

  async saveRule() {
    try {
      const formData = this.collectFormData();
      
      if (!this.validateFormData(formData)) {
        return;
      }

      const rule = this.buildRuleFromForm(formData);
      
      if (this.currentEditingRule) {
        // 编辑现有规则
        const response = await chrome.runtime.sendMessage({
          type: 'UPDATE_RULE',
          ruleId: this.currentEditingRule.id,
          rule: rule
        });

        if (response.success) {
          this.rules.set(this.currentEditingRule.id, { ...rule, id: this.currentEditingRule.id });
          this.showNotification('规则更新成功', 'success');
        } else {
          this.showNotification(response.error || '更新规则失败', 'error');
        }
      } else {
        // 添加新规则
        const response = await chrome.runtime.sendMessage({
          type: 'ADD_RULE',
          rule: rule
        });

        if (response.success) {
          this.rules.set(response.ruleId, { ...rule, id: response.ruleId });
          this.showNotification('规则添加成功', 'success');
        } else {
          this.showNotification(response.error || '添加规则失败', 'error');
        }
      }

      this.closeRuleModal();
      this.renderRules();
    } catch (error) {
      console.error('保存规则失败:', error);
      this.showNotification('保存规则失败', 'error');
    }
  }

  collectFormData() {
    const selectedRequest = this.pageRequests.get(document.getElementById('apiSelector').value);
    
    return {
      // 从选中的请求中获取URL和方法，而不是从表单
      url: selectedRequest ? selectedRequest.url : '',
      method: selectedRequest ? selectedRequest.method : '',
      enableRequestMod: document.getElementById('enableRequestMod').checked,
      enableResponseMod: document.getElementById('enableResponseMod').checked,
      requestHeaders: document.getElementById('requestHeaders').value.trim(),
      requestBody: document.getElementById('requestBody').value.trim(),
      responseStatus: parseInt(document.getElementById('responseStatus').value),
      responseDelay: parseInt(document.getElementById('responseDelay').value),
      responseHeaders: document.getElementById('responseHeaders').value.trim(),
      responseBody: document.getElementById('responseBody').value.trim()
    };
  }

  validateFormData(data) {
    if (!data.url) {
      this.showNotification('请选择要拦截的接口', 'error');
      return false;
    }

    if (!data.enableRequestMod && !data.enableResponseMod) {
      this.showNotification('请至少启用请求修改或响应修改', 'error');
      return false;
    }

    // 验证JSON格式
    try {
      if (data.enableRequestMod) {
        if (data.requestHeaders) JSON.parse(data.requestHeaders);
        if (data.requestBody) JSON.parse(data.requestBody);
      }
      if (data.enableResponseMod) {
        if (data.responseHeaders) JSON.parse(data.responseHeaders);
        if (data.responseBody) JSON.parse(data.responseBody);
        
        // 响应修改必须有响应体或状态码修改
        if (!data.responseBody && data.responseStatus === 200) {
          this.showNotification('启用响应修改时，请至少提供响应体或修改状态码', 'error');
          return false;
        }
      }
    } catch (error) {
      this.showNotification('JSON格式错误: ' + error.message, 'error');
      return false;
    }

    return true;
  }

  buildRuleFromForm(data) {
    // 自动生成规则名称
    const urlPath = data.url ? new URL(data.url).pathname : 'unknown';
    const ruleName = `${data.method} ${urlPath}`;
    
    const rule = {
      name: ruleName,
      urlPattern: data.url,
      method: data.method,
      enabled: true
    };

    if (data.enableRequestMod) {
      rule.requestModification = {};
      if (data.requestHeaders) {
        rule.requestModification.headers = JSON.parse(data.requestHeaders);
      }
      if (data.requestBody) {
        rule.requestModification.body = JSON.parse(data.requestBody);
      }
    }

    if (data.enableResponseMod) {
      rule.responseModification = {
        status: data.responseStatus,
        delay: data.responseDelay
      };
      if (data.responseHeaders) {
        rule.responseModification.headers = JSON.parse(data.responseHeaders);
      }
      if (data.responseBody) {
        rule.responseModification.body = JSON.parse(data.responseBody);
      }
    }

    return rule;
  }

  renderRules() {
    const container = document.getElementById('rulesList');
    const emptyState = document.getElementById('emptyState');
    
    if (this.rules.size === 0) {
      container.style.display = 'none';
      emptyState.style.display = 'block';
      return;
    }

    container.style.display = 'block';
    emptyState.style.display = 'none';
    
    container.innerHTML = Array.from(this.rules.values())
      .map(rule => this.createRuleElement(rule))
      .join('');

    // 添加事件监听器
    this.attachRuleEventListeners();
  }

  createRuleElement(rule) {
    const badges = [];
    
    if (rule.method) {
      badges.push(`<span class="rule-badge badge-method">${rule.method}</span>`);
    }
    
    badges.push(
      `<span class="rule-badge ${rule.enabled ? 'badge-enabled' : 'badge-disabled'}">
        ${rule.enabled ? '已启用' : '已禁用'}
      </span>`
    );

    return `
      <div class="rule-item" data-rule-id="${rule.id}">
        <div class="rule-header">
          <div class="rule-name">${this.escapeHtml(rule.name)}</div>
          <div class="rule-actions">
            <label class="toggle-switch">
              <input type="checkbox" ${rule.enabled ? 'checked' : ''} data-action="toggle">
              <span class="toggle-slider"></span>
            </label>
            <button class="btn btn-secondary btn-small" data-action="edit">编辑</button>
            <button class="btn btn-danger btn-small" data-action="delete">删除</button>
          </div>
        </div>
        <div class="rule-meta">
          ${badges.join('')}
        </div>
        <div class="rule-url">${this.escapeHtml(rule.urlPattern)}</div>
      </div>
    `;
  }

  attachRuleEventListeners() {
    document.querySelectorAll('.rule-item').forEach(item => {
      const ruleId = item.dataset.ruleId;
      
      // 切换启用/禁用
      const toggle = item.querySelector('[data-action="toggle"]');
      toggle.addEventListener('change', () => this.toggleRule(ruleId));

      // 编辑
      const editBtn = item.querySelector('[data-action="edit"]');
      editBtn.addEventListener('click', () => this.editRule(ruleId));

      // 删除
      const deleteBtn = item.querySelector('[data-action="delete"]');
      deleteBtn.addEventListener('click', () => this.deleteRule(ruleId));
    });
  }

  async toggleRule(ruleId) {
    try {
      const response = await chrome.runtime.sendMessage({
        type: 'TOGGLE_RULE',
        ruleId: ruleId
      });

      if (response.success) {
        const rule = this.rules.get(ruleId);
        if (rule) {
          rule.enabled = response.enabled;
          this.renderRules();
        }
      } else {
        this.showNotification(response.error || '切换规则状态失败', 'error');
      }
    } catch (error) {
      console.error('切换规则状态失败:', error);
      this.showNotification('切换规则状态失败', 'error');
    }
  }

  editRule(ruleId) {
    const rule = this.rules.get(ruleId);
    if (rule) {
      this.openRuleModal(rule);
    }
  }

  async deleteRule(ruleId) {
    const rule = this.rules.get(ruleId);
    if (rule && confirm(`确定要删除规则 "${rule.name}" 吗？`)) {
      try {
        const response = await chrome.runtime.sendMessage({
          type: 'DELETE_RULE',
          ruleId: ruleId
        });

        if (response.success) {
          this.rules.delete(ruleId);
          this.renderRules();
          this.showNotification('规则删除成功', 'success');
        } else {
          this.showNotification(response.error || '删除规则失败', 'error');
        }
      } catch (error) {
        console.error('删除规则失败:', error);
        this.showNotification('删除规则失败', 'error');
      }
    }
  }

  filterRules(searchTerm) {
    const items = document.querySelectorAll('.rule-item');
    const term = searchTerm.toLowerCase();

    items.forEach(item => {
      const name = item.querySelector('.rule-name').textContent.toLowerCase();
      const url = item.querySelector('.rule-url').textContent.toLowerCase();
      const matches = name.includes(term) || url.includes(term);
      item.style.display = matches ? 'block' : 'none';
    });
  }

  renderLogs() {
    const container = document.getElementById('logsList');
    
    if (this.logs.length === 0) {
      container.innerHTML = '<div class="empty-state"><p>暂无请求日志</p></div>';
      return;
    }

    container.innerHTML = this.logs
      .slice(-50) // 只显示最近50条
      .reverse()
      .map(log => this.createLogElement(log))
      .join('');
  }

  createLogElement(log) {
    return `
      <div class="log-item">
        <div class="log-url">${this.escapeHtml(log.url)}</div>
        <div class="log-time">${new Date(log.timestamp).toLocaleString()}</div>
      </div>
    `;
  }

  clearLogs() {
    this.logs = [];
    this.renderLogs();
    this.showNotification('日志已清除', 'success');
  }

  showNotification(message, type = 'info') {
    // 简单的通知实现
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    Object.assign(notification.style, {
      position: 'fixed',
      top: '20px',
      right: '20px',
      padding: '12px 16px',
      borderRadius: '6px',
      backgroundColor: type === 'error' ? '#fee2e2' : type === 'success' ? '#dcfce7' : '#e0f2fe',
      color: type === 'error' ? '#991b1b' : type === 'success' ? '#166534' : '#0c4a6e',
      border: `1px solid ${type === 'error' ? '#fecaca' : type === 'success' ? '#bbf7d0' : '#bae6fd'}`,
      zIndex: '10000',
      fontSize: '14px',
      fontWeight: '500',
      boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
    });

    document.body.appendChild(notification);

    setTimeout(() => {
      notification.remove();
    }, 3000);
  }

  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// 启动popup管理器
document.addEventListener('DOMContentLoaded', () => {
  new PopupManager();
});